<template>
  <a-modal
    width="1000px"
    v-model:visible="visible"
    :footer="null"
    hide-title
    :modal-style="{ backgroundColor: '#e5e5e5' }"
    :body-style="{ padding: 0 }"
    unmount-on-close
  >
    <div class="w-full h-80vh flex preview-page">
      <div class="w-90n h-full">
        <a-scrollbar
          ref="scrollbarRefL"
          style="width: 100%; height: 100%; overflow: auto; padding: 18px; box-sizing: border-box"
          @scroll="(e) => scrollFun(e, 'l')"
        >
          <div class="flex flex-j-c my-6">
            <a-button type="text" :loading="loading" @click="nextPage('t')">
              {{ hasPreT ? '点击加载历史数据' : '没有更多了' }}
            </a-button>
          </div>
          <template v-for="item in tableData" :key="item.position">
            <template v-if="item.goodsLists.length > 0">
              <div
                v-for="goods in item.goodsLists"
                :key="`${item.position}♠${goods.goodsId}`"
                class="bgfff h-34n w-full round-4 box-border px-12 py-14 flex overflow-hidden mb-16 cursor-pointer"
                :class="
                  chooseCurrentId == `${item.position}♠${goods.goodsId}`
                    ? 'active-box'
                    : 'nomal-box'
                "
                :id="`${item.position}♠${goods.goodsId}`"
                @click="handleGoodsClick(`${item.position}♠${goods.goodsId}`)"
              >
                <a-image width="100px" height="100px" :src="goods.picUrl" class="mr-14"> </a-image>
                <div class="flex-1 flex-col flex-j-b overflow-hidden mt-6">
                  <div class="text-overflow-2 w-full">{{ goods.title }}</div>
                  <div class="w-full flex flex-j-b flex-a-c no-wrap">
                    <span class="text999">月销:{{ goods.monthSales || 0 }}</span>
                    <span class="textff8d1a">赚:￥{{ goods.commissionRate || 0 }}</span>
                  </div>
                  <div class="textff0000 text-size-16 font-bold">
                    ￥{{ goods.actualPrice || 0 }}
                  </div>
                </div>
              </div>
            </template>
          </template>
          <div class="flex flex-j-c my-6">
            <a-button type="text" :loading="loading" @click="nextPage('b')">
              {{ hasPreB ? '点击加载最新数据' : '没有更多了' }}
            </a-button>
          </div>
        </a-scrollbar>
      </div>
      <div class="flex-1 h-full flex-col">
        <div class="w-full h-15n bgfff box-border px-16 flex flex-a-c flex-j-b">
          <div>
            <template v-if="currentGroup">
              <a-image :src="currentGroup.pic" width="42" />
              <span class="text-size-16 font-bold ml-8">{{ currentGroup.name }}</span>
            </template>
          </div>
          <icon-close size="20" class="cursor-pointer" @click="visible = false" />
        </div>
        <div class="flex-1 w-full bgef m-relative overflow-hidden">
          <div class="m-absolute t-0 b-0 l-0 r-0">
            <a-scrollbar
              ref="scrollbarRefR"
              style="
                width: 100%;
                height: 100%;
                overflow: auto;
                padding: 14px 18px 0;
                box-sizing: border-box;
              "
            >
              <!-- <div class="flex flex-j-c my-6">
                <a-button type="text" :loading="loading" @click="nextPage('t')">
                  {{ hasPre ? '点击加载历史数据' : '没有更多了' }}
                </a-button>
              </div> -->
              <a-checkbox-group class="w-full" v-model="selectedKeys">
                <template v-for="item in msgList" :key="item.position">
                  <div
                    v-if="item.content"
                    :id="item.position"
                    class="w-full pl-6 pr-16 box-border mb-20"
                  >
                    <div class="mb-14 flex-center">
                      <div class="textfff bg203 w-fit px-10 py-6 round-4">{{ item.createAt }}</div>
                    </div>
                    <div class="flex flex-j-e">
                      <div class="w-30 h-30">
                        <a-checkbox :value="item.position"></a-checkbox>
                      </div>
                      <a-avatar :size="32" shape="square">
                        <a-image
                          :src="item.senderInfo.avatar"
                          class="w-fit bgfff overflow-hidden"
                        ></a-image>
                      </a-avatar>
                      <div class="ml-8 flex-1">
                        <div
                          class="w-fit bgfff overflow-hidden round-10"
                          v-if="item.messageType == 3"
                        >
                          <a-image width="120" :src="item.content"></a-image>
                        </div>
                        <div class="w-full w-fit" v-if="item.messageType == 47">
                          <a-image
                            v-if="isImage(item.content)"
                            height="50"
                            :src="item.content"
                          ></a-image>
                          <div
                            v-else
                            v-html="item.content"
                            :style="{ 'white-space': 'pre-wrap' }"
                          ></div>
                        </div>
                        <div
                          class="w-fit bgfff flex-center p-8 box-border round-10 space-pre-line"
                          v-else-if="item.messageType == 1"
                        >
                          {{ item.content }}
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </a-checkbox-group>
              <!-- <div class="flex flex-j-c my-6">
                <a-button type="text" :loading="loading" @click="nextPage('b')">
                  {{ hasPre ? '点击加载最新数据' : '没有更多了' }}
                </a-button>
              </div> -->
            </a-scrollbar>
            <div class="m-absolute r-6n b-7n z-index-10" v-if="selectedKeys.length">
              <a-space>
                <a-button type="primary" shape="round" @click="openChooseGroup">一键发群</a-button>
                <a-button type="outline" shape="round" @click="selectedKeys = []">取消</a-button>
              </a-space>
            </div>
          </div>
        </div>
        <div class="w-full h-15n flex-center box-border px-14">
          <a-input-search size="large" placeholder="支持 商品标题/文案/链接/口令 搜索" />
        </div>
      </div>
    </div>
    <PersonalGroupModal
      ref="PersonalGroupModalRef"
      :personalGroupList="personalGroupList"
      @afterChooseGroup="afterChooseGroup"
    />
  </a-modal>
</template>

<script setup>
import { Message, Modal } from '@arco-design/web-vue'
import PersonalGroupModal from './personalGroupModal.vue'
import { IconClose } from '@arco-design/web-vue/es/icon'
import { nextTick } from 'vue'
const props = defineProps(['personalGroupList'])
const { ipcRenderer } = window.electron
const visible = ref(false)
const loading = ref(false)
const hasPreT = ref(true)
const hasPreB = ref(true)
const scrollbarRefL = ref()
const scrollbarRefR = ref()
const chooseCurrentId = ref()
const tableData = ref([])
const msgList = ref([])
const selectedKeys = ref([])
const PersonalGroupModalRef = ref()
const firstLoad = ref(true)
const formData = reactive({
  wsMsgType: 'getSourceChatroomPreview',
  position: 0,
  sourceChatroomId: undefined,
  type: 1,
  keyword: ''
})
const currentGroup = ref()

// 监听WebSocket消息
ipcRenderer.on('webSocketMessage', async (event, res) => {
  if (res?.data?.wsMsgType) {
    switch (res?.data?.wsMsgType) {
      case 'getSourceChatroomPreview':
        console.log(res?.data)
        if (res.code == 200) {
          const result = res?.data?.list ?? []
          if (formData.type == 2) {
            hasPreT.value = result.length > 0
          } else {
            hasPreB.value = result.length > 0
          }
          let elLB, elLT
          if (result.length) {
            if (!firstLoad.value) {
              const itemB = tableData.value.findLast(
                (element) => element.goodsLists && element.goodsLists.length > 0
              )
              const itemT = tableData.value.find(
                (element) => element.goodsLists && element.goodsLists.length > 0
              )
              if (itemB) {
                const idLB = `${itemB.position}♠${itemB.goodsLists[itemB.goodsLists.length - 1].goodsId}`
                elLB = document.getElementById(idLB)
              }
              if (itemT) {
                const idLT = `${itemT.position}♠${itemT.goodsLists[itemT.goodsLists.length - 1].goodsId}`
                elLT = document.getElementById(idLT)
              }
              // const idRB = msgList.value[msgList.value.length - 1].position
              // const idRT = msgList.value[0].position
              // const elRB = document.getElementById(idRB)
              // const elRT = document.getElementById(idRT)
            }
            if (formData.type == 2) {
              tableData.value = result.concat(tableData.value)
            } else {
              tableData.value = tableData.value.concat(result)
            }
            msgList.value = JSON.parse(JSON.stringify(tableData.value))
          }
          if (firstLoad.value) {
            nextTick(() => {
              const itemLast = tableData.value.findLast(
                (element) => element.goodsLists && element.goodsLists.length > 0
              )
              const idR = msgList.value[msgList.value.length - 1].position
              const idL = `${itemLast.position}♠${itemLast.goodsLists[itemLast.goodsLists.length - 1].goodsId}`
              const elR = document.getElementById(idR)
              const elL = document.getElementById(idL)
              setTimeout(() => {
                if (elR) scrollbarRefR.value?.scrollTop(elR.offsetTop + elR.offsetHeight + 200)
                if (elL) scrollbarRefL.value?.scrollTop(elL.offsetTop + elL.offsetHeight + 200)
              }, 200)
            })
            firstLoad.value = false
          } else {
            if (formData.type == 2) {
              nextTick(() => {
                if (elLT) scrollbarRefL.value?.scrollTop(elLT.offsetTop - 10)
              })
            } else {
              console.log(elLB)
              nextTick(() => {
                if (elLB) scrollbarRefL.value?.scrollTop(elLB.offsetTop + elLB.offsetHeight + 10)
              })
            }
          }
        } else {
          Message.error(res.message)
        }
        loading.value = false
        break
      case 'getSourceChatroomPreviewSearchList':
        msgList.value = res?.data?.list ?? []
        nextTick(() => {
          const id = chooseCurrentId.value?.split('♠')[0]
          const el = document.getElementById(id)
          scrollbarRefR.value?.scrollTo({
            top: el.offsetTop
          })
        })
        break
    }
  }
})

// 打开编辑框并回显表单值
const openPreviewModal = (record) => {
  visible.value = true
  formData.sourceChatroomId = record.id
  currentGroup.value = record
  tableData.value = []
  selectedKeys.value = []
  getSourceChatroomPreview()
}

// 获取预览数据
const getSourceChatroomPreview = () => {
  loading.value = true
  setTimeout(() => {
    if (loading.value) loading.value = false
  }, 2000)
  console.log({ ...formData })
  ipcRenderer.send('sendToWebSocket', { ...formData })
}

// 获取历史数据
const nextPage = (str) => {
  if (loading.value) return
  const length = tableData.value.length
  if (length) {
    formData.position =
      str === 't' ? tableData.value[0].position : tableData.value[length - 1].position
  } else {
    formData.position = 0
  }

  formData.type = str === 't' ? 2 : 1
  getSourceChatroomPreview()
}

// 防抖
const throttle = (fn, time = 800) => {
  let timer = null
  return function () {
    if (!timer) {
      timer = setTimeout(function () {
        fn()
        timer = null
      }, time)
    }
  }
}

/*** 监听滚动条*/
const scrollFun = (e) => {
  // if (e.target.scrollTop === 0) {
  //   throttle(nextPage('t'), 500)
  // } else if (Math.ceil(e.target.scrollTop + e.target.clientHeight) >= e.target.scrollHeight) {
  //   throttle(nextPage('b'), 500)
  // }
}

const checkImgExists = (content) => {
  const ImgObj = new Image() //判断图片是否存在
  ImgObj.src = content
  if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
    return true
  } else {
    return false
  }
}

const isImage = (content) => {
  /*
        stodownload 表情包 分割线
        images 商品图
        jpg 图片
        wx_emoji
        vweixinf.tc.qq.com
        */
  return (
    content.indexOf('images') != -1 ||
    content.indexOf('stodownload') != -1 ||
    content.indexOf('wx_emoji') != -1 ||
    content.indexOf('vweixinf') != -1 ||
    content.indexOf('jpg') != -1 ||
    checkImgExists(content)
  )
}

// 点击一键发群
const openChooseGroup = async () => {
  PersonalGroupModalRef?.value.openGroupModal()
}

// 选择转发群
const afterChooseGroup = (groups) => {
  const result = tableData.value.filter((item) => {
    return selectedKeys.value.includes(item.position)
  })
  const res = []
  result.forEach((element) => {
    groups.forEach((item) => {
      console.log(element, item)
      res.push({
        msg: element.content,
        wx_type: element.messageType,
        wxid1: element.groupNo,
        wxid3: item,
        recvWxid: element.sourceChatroomId,
        msgid: element.position,
        official: true
      })
    })
  })
  ipcRenderer.send('insertMsgs', res)
  selectedKeys.value = []
  Message.success('操作成功')
}

// 商品点击
const handleGoodsClick = (id) => {
  chooseCurrentId.value = id
  const position = id.split('♠')[0]
  selectedKeys.value = []
  ipcRenderer.send('sendToWebSocket', {
    wsMsgType: 'getSourceChatroomPreviewSearchList',
    position,
    sourceChatroomId: formData.sourceChatroomId
  })
}

defineExpose({ openPreviewModal })
</script>
<style scoped lang="scss">
.arco-scrollbar {
  height: 100%;
}
.h-80vh {
  height: 80vh;
}
.bgef {
  background: #efefef;
}
.textff8d1a {
  color: #ff8d1a;
}
.textff0000 {
  color: #ff0000;
}
.preview-page {
  .arco-input-search {
    border-radius: 20px;
  }
}
.space-pre-line {
  white-space: pre-line;
  word-break: break-all;
}
.active-box {
  box-shadow: rgba(255, 0, 0, 1) solid 2px;
  border: 2px solid rgba(255, 0, 0, 1);
}
.nomal-box {
  box-shadow: transparent solid 2px;
  border: 2px solid transparent;
}
.bg203 {
  background: rgba(203, 203, 203, 1);
}
</style>
